<?php

namespace App\Containers\AppSection\Ban\Actions;

use App\Containers\AppSection\Authentication\Tasks\RevokeTokensTask;
use App\Containers\AppSection\Ban\Tasks\CreateBanTask;
use App\Containers\AppSection\Log\Tasks\CreateLogTask;
use App\Containers\AppSection\Profile\Tasks\FindLatestProfileByUserIdTask;
use App\Containers\AppSection\User\Tasks\FindUserByIdTask;
use App\Containers\AppSection\User\Tasks\UpdateUserTask;
use App\Ship\Exceptions\BadRequestException;
use App\Ship\Parents\Actions\Action;
use App\Ship\Parents\Requests\Request;

class BanUserAction extends Action
{
    public function run($id, Request $request)
    {
        $user = app(FindUserByIdTask::class)->run($id);

        if ($user->isBanned() || $user->trashed()) {
            throw new BadRequestException('Пользователь уже заблокирован!');
        }

        $ban = app(CreateBanTask::class)->run([
            'user_id' => $user->id,
            'banned_by_id' => $request->profile()->id,
            'ban_comment' => $request->getInputByKey('comment'),
            'banned_at' => now(),
        ]);

        app(UpdateUserTask::class)->run(['ban_id' => $ban->id, 'deleted_at' => now()], $user->id);

        $profile = app(FindLatestProfileByUserIdTask::class)->run($user->id);

        app(RevokeTokensTask::class)->run($user->id);

        app(CreateLogTask::class)->run($profile->id, "Пользователь №{$user->id} заблокирован (админ)", 'ban_user');
        app(CreateLogTask::class)->run($request->profile()->id, "Пользователь №{$user->id} заблокирован", 'ban_user');
    }
}
